package com.itlaobing.dbhelper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.tomcat.dbcp.dbcp2.DriverManagerConnectionFactory;

public class Dbhelper {
	public String url = "jdbc:mysql://localhost:3306/server_test1?useSSL=false&serverTimezone=GMT%2B8";
	public String user = "root";
	public String pass = "";
	public String driver = "com.mysql.cj.jdbc.Driver";
	public Connection con = null;
	public PreparedStatement presta = null;
	public ResultSet rs = null;
	
	//获取数据库连接
	public void getConnection() throws ClassNotFoundException, SQLException {
		//加载数据库驱动
		Class.forName(driver);
		//获取数据库连接
		con = DriverManager.getConnection(url,user,pass);
	}
	
	//为语句发送器添加参数
	public void setValue(Object...objects) throws SQLException {
		if(objects != null&&objects.length != 0) {
			for(int i = 0 ; i < objects.length ;i++) {
				presta.setObject(i+1,objects[i]);
			}
		}
	}
	
	
	//执行增删改sql语句
	public int executeUpdate(String sql,Object...objects) throws ClassNotFoundException, SQLException {
		//获取数据库连接
		getConnection();
		//创建语句发送器并拼写sql
		presta = con.prepareStatement(sql);
		//添加参数
		setValue(objects);
		//执行sql语句
		return presta.executeUpdate();
	}
	
	//执行查询sql语句
	public ResultSet executeQuery(String sql,Object...objects) throws  SQLException, ClassNotFoundException {
		//获取数据库连接
		getConnection();
		//创建sql语句发送器
		presta = con.prepareStatement(sql);
		//添加参数
		setValue(objects);
		//执行sql
		rs = presta.executeQuery();
		return rs;
	}
	
	//关闭资源
	public void close() throws SQLException {
		if(rs != null) {
			rs.close();
		}
		if(con != null) {
			con.close();
		}
		if(presta != null) {
			presta.close();
		}
	}
}
